package com.example.demo.controller;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Message;
import com.example.demo.model.User;
import com.example.demo.services.IMessageService;
import com.example.demo.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author baekhyun
 **/
@Slf4j
@Api(tags = "站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    /**
     * 发送站内信
     * @param request
     * @param receiveUserId
     * @param content
     * @return
     */
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接受用户Id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("站内信内容") @RequestParam("content") @NonNull String content){
        //获取发送用户信息
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //判断是否被禁言
        if (user.getState()!=0){
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能给自己发送
        if (user.getId()==receiveUserId){
            //打印日志
            log.warn("不能给自己发送站内信，postUserId="+user.getId()+",receiveUserId="+receiveUserId);
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //查询接收用户
        User receiveUser=userService.selectById(receiveUserId);
        //目标用户不存在
        if (receiveUser==null || receiveUser.getDeleteState()!=0){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //构造对象
        Message message=new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //调用DAO
        messageService.create(message);
        //返回结果
        return AppResult.success();
    }

    /**
     * 获取站内信未读消息个数
     * @param request
     * @return
     */
    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取发送用户信息
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //查询未读消息个数
        Integer result= messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(result);
    }

    /**
     * 查询用户的所有站内信
     * @param request
     * @return
     */
    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取当前登录用户
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //获取用户站内信
        List<Message> result=messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(result);
    }

    /**
     * 更新状态为已读
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信Id") @RequestParam("id") @NonNull Long id){
        //根据Id查询内容
        Message message=messageService.selectById(id);
        //获取用户信息
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //接收方不是自己
        if (message!=null && user.getId()!= message.getReceiveUserId()){
            //打印日志
            log.warn("查询了不属于自己的站内信：userId="+user.getId()+",receiveUserId="+message.getReceiveUserId());
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED);
        }
        //更新为已读状态
        messageService.updateStateById(message.getId(), (byte) 1);
        //返回结果
        return AppResult.success();
    }

    /**
     * 回复站内信
     * @param request
     * @param repliedId
     * @param content
     * @return
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content){
        //校验当前登录用户的状态
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验要回复的站内信状态
        Message existsMessage=messageService.selectById(repliedId);
        if (existsMessage==null || existsMessage.getDeleteState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.MESSAGE_NOT_EXISTS);
        }
        //不能给自己回复
        if (user.getId()==existsMessage.getPostUserId()){
            //返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        //构造对象
        Message message=new Message();
        message.setPostUserId(user.getId());//发送者
        message.setReceiveUserId(existsMessage.getPostUserId());//接收者
        message.setContent(content);//内容
        //调用service
        messageService.reply(repliedId,message);
        //返回结果
        return AppResult.success();
    }
}
